//
//  MyViewController.m
//  UGoods
//
//  Created by 宝银 on 16/1/15.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "MyViewController.h"
#import "BaseTableView.h"
#import "NightMode.h"
#import "ConstantsDefine.h"
#import "CollectViewController.h"
@interface MyViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSArray *section1Array;
@property (nonatomic, retain) NSArray *section2Array;
@property (nonatomic, assign) CGFloat cacheSize;
@property (nonatomic, retain) UIImageView *backView;

@end

@implementation MyViewController

- (void)createTableView{
    self.section1Array = @[@"清除缓存", @"夜间模式"];
    self.section2Array = @[@"订单信息"];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.backView addSubview:_tableView];
    [_tableView release];
    
    UIImageView *headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250 * HEIGHT)];
    headerImageView.image = [UIImage imageNamed:@"d55665283fe1900e6761784d8644f8c6"];
    self.tableView.tableHeaderView = headerImageView;
    [headerImageView release];
    

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    } else {
        return 1;
    }
}

// 创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell1"];
            cell.textLabel.text = _section1Array[indexPath.row];
            if (indexPath.row == 0) {
//                float sum = [self folderSizeAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]];
                
//                NSString *str = [[NSString stringWithFormat:@"%.1lf",sum] stringByAppendingString:@"M"];
//                cell.detailTextLabel.text = str;
            } else if (indexPath.row == 1) {
                UISwitch *nightSwitch = [[UISwitch alloc] init];
                cell.accessoryView = nightSwitch;
                [nightSwitch addTarget:self action:@selector(handleNight:) forControlEvents:UIControlEventValueChanged];
            }
        }
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
            cell.textLabel.text = _section2Array[indexPath.row];
        }
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

// 夜间模式点击事件
- (void)handleNight:(UISwitch *)sender {
    [NightMode nightModeSharedInstance].isNight = sender.on;
}

// cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 清除缓存cell
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            float sum = [self folderSizeAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]];
            
            NSString *str = [[NSString stringWithFormat:@"%.1lf",sum] stringByAppendingString:@"M"];
            NSString *str1 = [NSString stringWithFormat:@"%@  是否全部删除缓存?", str];
            // 弹窗
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:str1 message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
                
                [self removeCache];
                
                NSString *path =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                NSString  *path1 = [path stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
                
                self.cacheSize =  [self fileSizeForDir:path1];
                
                
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                
                
            }];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
            
            [alert addAction:cancleAction];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            NSLog(@"清除缓存");

        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            CollectViewController *collect = [[CollectViewController alloc] init];
            [self.navigationController pushViewController:collect animated:YES];
            [collect release];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 页面将要消失时显示navigationController，使下一页面出现navigationController
    self.navigationController.navigationBarHidden = NO;
    
}

#pragma mark - 页面将要出现的时候
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    [self hidesTabBar:NO];
    
    // 页面将要出现时隐藏navigationController
    self.navigationController.navigationBarHidden = YES;
    
    NSString *path =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString  *path1 = [path stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
    
    _cacheSize =  [self fileSizeForDir:path1];
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    
    [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
    
}

#pragma mark - 清除缓存部分*******************
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//遍历文件夹获得文件夹大小，返回多少M
- (float) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1000.0*1000.0);
}

#pragma mark - 清除
-(void)removeCache
{
    //===============清除缓存==============
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    //    NSLog(@"文件数 ：%d",[files count]);
    for (NSString *p in files)
    {
        NSError *error;
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
}

#pragma mark - 计算文件夹下文件的总大小
- (float)fileSizeForDir:(NSString*)path {
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    
    float size =0;
    
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    for(int i = 0; i < [array count]; i++) {
        
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        
        NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
        
        size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
        
    }
    [fileManager release];
    return size;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.backView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    _backView.userInteractionEnabled = YES;
    _backView.image = [UIImage imageNamed:@"72e5b1802607eb90b22e44ea980a3257"];
    [self.view addSubview:_backView];
    [_backView release];
    [self createTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
